"use client"

import { useEffect, useState } from "react"
import { MVFilters } from "@/components/mv/mv-filters"
import { MVGrid } from "@/components/mv/mv-grid"
import { fetchMVs } from "@/lib/api-client"
import type { MV } from "@/types/mv"
import { Skeleton } from "@/components/ui/skeleton"

export default function MVPage() {
  const [selectedRegion, setSelectedRegion] = useState("全部")
  const [selectedVersion, setSelectedVersion] = useState("全部")
  const [sortBy, setSortBy] = useState<"最新" | "最热">("最新")
  const [mvs, setMvs] = useState<MV[]>([])
  const [loading, setLoading] = useState(true)
  const [page, setPage] = useState(1)
  const [hasMore, setHasMore] = useState(true)

  // 将区域和版本选项映射到API参数
  const getRegionId = (region: string) => {
    const regionMap: Record<string, number | undefined> = {
      全部: undefined,
      内地: 1,
      港台: 2,
      欧美: 3,
      韩国: 4,
      日本: 5,
    }
    return regionMap[region]
  }

  const getVersionId = (version: string) => {
    const versionMap: Record<string, number | undefined> = {
      全部: undefined,
      MV: 1,
      现场: 2,
      翻唱: 3,
      舞蹈: 4,
      影视: 5,
      综艺: 6,
      儿歌: 7,
    }
    return versionMap[version]
  }

  const getSortParam = (sort: "最新" | "最热") => {
    return sort === "最新" ? "latest" : "popular"
  }

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true)
      try {
        const response = await fetchMVs({
          page: 1,
          limit: 20,
          regionId: getRegionId(selectedRegion),
          versionId: getVersionId(selectedVersion),
          sort: getSortParam(sortBy),
        })

        setMvs(response.items)
        setHasMore(response.items.length < response.total)
        setPage(1)
      } catch (error) {
        console.error("获取MV列表失败:", error)
        setMvs([])
      } finally {
        setLoading(false)
      }
    }

    fetchData()
  }, [selectedRegion, selectedVersion, sortBy])

  const loadMore = async () => {
    if (loading || !hasMore) return

    try {
      setLoading(true)
      const nextPage = page + 1

      const response = await fetchMVs({
        page: nextPage,
        limit: 20,
        regionId: getRegionId(selectedRegion),
        versionId: getVersionId(selectedVersion),
        sort: getSortParam(sortBy),
      })

      setMvs((prev) => [...prev, ...response.items])
      setHasMore(response.items.length < response.total)
      setPage(nextPage)
    } catch (error) {
      console.error("加载更多MV失败:", error)
    } finally {
      setLoading(false)
    }
  }

  return (
      <div className="min-h-screen">
        <div className="container mx-auto px-4 py-8">
          <MVFilters
              selectedRegion={selectedRegion}
              selectedVersion={selectedVersion}
              onRegionChange={setSelectedRegion}
              onVersionChange={setSelectedVersion}
          />
          <div className="mt-8">
            <div className="flex items-center justify-between mb-6">
              <h1 className="text-2xl font-bold">全部MV</h1>
              <div className="flex items-center gap-2">
                <button
                    onClick={() => setSortBy("最新")}
                    className={`px-3 py-1 rounded-full text-sm ${
                        sortBy === "最新"
                            ? "bg-primary text-primary-foreground"
                            : "text-muted-foreground hover:text-foreground"
                    }`}
                >
                  最新
                </button>
                <button
                    onClick={() => setSortBy("最热")}
                    className={`px-3 py-1 rounded-full text-sm ${
                        sortBy === "最热"
                            ? "bg-primary text-primary-foreground"
                            : "text-muted-foreground hover:text-foreground"
                    }`}
                >
                  最热
                </button>
              </div>
            </div>

            {loading && mvs.length === 0 ? (
                <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
                  {Array.from({ length: 8 }).map((_, index) => (
                      <div key={index} className="space-y-2">
                        <Skeleton className="aspect-video w-full rounded-lg" />
                        <Skeleton className="h-4 w-3/4" />
                        <Skeleton className="h-3 w-1/2" />
                      </div>
                  ))}
                </div>
            ) : (
                <>
                  <MVGrid mvs={mvs} />

                  {hasMore && (
                      <div className="mt-8 flex justify-center">
                        <button
                            onClick={loadMore}
                            disabled={loading}
                            className="px-4 py-2 bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/80 disabled:opacity-50"
                        >
                          {loading ? "加载中..." : "加载更多"}
                        </button>
                      </div>
                  )}
                </>
            )}
          </div>
        </div>
      </div>
  )
}

